<template>
  <div class="card-list" ref="content">
    <div class="operate-panel">
      <div class="tabs-menu">
        <span
          v-for="(m, i) in menu"
          :key="i"
          :class="{ 'tabs-item': true, 'tabs-active': isCurrentMenuActive(i) }"
          @click="handleMenuItemClick(i)"
        >
          {{ m }}
        </span>
      </div>
      <a-button type="primary" icon="plus" @click="handleCreateExamBtnClick">创建考试</a-button>
    </div>

    <a-list :grid="{ gutter: 24, lg: 3, md: 2, sm: 1, xs: 1 }" :dataSource="dataSource">
      <a-list-item slot="renderItem" slot-scope="item">
        <a-card :hoverable="true" @click="joinExam(item.id)">
          <a-card-meta>
            <div style="margin-bottom: 3px" slot="title">{{ item.title }}</div>
            <a-avatar class="card-avatar" slot="avatar" :src="getImageSrc(item.examId * 3)" size="large" />
            <div class="meta-content" slot="description">{{ item.content }}</div>
          </a-card-meta>
          <template class="ant-card-actions" slot="actions">
            <a>满分：{{ item.score }}分</a>
            <a>限时：{{ item.elapse }}分钟</a>
          </template>
        </a-card>
      </a-list-item>
    </a-list>

    <a-modal
      title="创建考试"
      :visible="createExamModalVisible"
      okText="创建"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :centered="true"
    >
      <a-form :form="form">
        <a-form-item label="选择考卷" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            :showSearch="true"
            style="width: 100%"
            @change="handleExamPaperSelectChange"
            v-decorator="['examPaper', { rules: [{ required: true, message: '请选择考卷!' }] }]"
          >
            <a-select-option v-for="ep in examPapers" :key="ep.id">{{ ep.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="考试名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['name', { rules: [{ required: true, message: '请填写考试名称!' }] }]" />
        </a-form-item>
        <a-form-item label="考试时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number
            :min="1"
            :max="200"
            v-decorator="['elapse', { initialValue: '90', rules: [{ required: true, message: '请设置考试的限时!' }] }]"
          />
          分钟
        </a-form-item>
        <a-form-item label="有效日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-range-picker v-decorator="['dateRange', { rules: [{ required: true, message: '请设置考试有效期!' }] }]" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getExamAll, getExamCardList } from '../../api/exam'
import { EXAM_MUTATION } from '../../store/mutation-types'

export default {
  name: 'ExamCardList',
  data() {
    return {
      description: '您可以随意点击下面的考试卡片开始一场属于您的考试',
      extraImage: 'https://gw.alipayobjects.com/zos/rmsportal/RzwpdLnhmvDJToTdfDPe.png',
      // dataSource: [],
      // examList: [],
      menu: ['所有考试', '已结束的考试', '可参加的考试', '未开始的考试'],
      currentMenuIndex: 0,
      createExamModalVisible: false,
      examPapers: [],
      selectedExamPaperId: '',
      form: this.$form.createForm(this),
    }
  },
  methods: {
    handleExamPaperSelectChange: function (examPaperId) {
      const selectedExamPaper = this.examPapers.find((e) => e.id === examPaperId)
      console.log({ selectedExamPaper })
      this.form.setFieldsValue({
        name: selectedExamPaper.name,
      })
    },
    queryAllExamPapers: function () {
      getExamAll().then((res) => {
        if (res.code === 0) {
          this.examPapers = res.data
        } else {
          this.$notification.error({
            message: '获取全部考卷的列表失败',
            description: res.msg,
          })
        }
      })
    },
    handleCreateExamBtnClick: function () {
      this.createExamModalVisible = true
    },
    handleModalOk: function () {
      this.form.validateFields((err, values) => {
        if (!err) {
          const selectedExamPaper = this.examPapers.find((e) => e.id === values.examPaper)
          this.$store.commit(EXAM_MUTATION.CREATE, {
            createExam: {
              ...selectedExamPaper,
              content: selectedExamPaper.desc,
              title: selectedExamPaper.name,
              name: values.name,
            },
          })
          this.createExamModalVisible = false
          this.form.resetFields()
        }
      })
    },
    handleModalCancel: function () {
      this.createExamModalVisible = false
      this.form.resetFields()
    },
    getImageSrc: function (srcId) {
      return `https://picsum.photos/id/${srcId}/300`
    },
    joinExam(id) {
      const routeUrl = this.$router.resolve({
        path: `/exam/${id}`,
      })
      window.open(routeUrl.href, '_blank')
    },
    isCurrentMenuActive: function (menuIndex) {
      return menuIndex === this.currentMenuIndex
    },
    handleMenuItemClick: function (menuIndex) {
      if (menuIndex !== this.currentMenuIndex) {
        this.currentMenuIndex = menuIndex
        // 骗人的条件筛选
        // switch (menuIndex) {
        //   case 0:
        //     this.dataSource = this.examList
        //     break
        //   case 1:
        //     this.dataSource = this.examList.slice(this.examList.length - 10, this.examList.length - 5)
        //     break
        //   case 2:
        //     this.dataSource = this.examList.slice(0, this.examList.length - 10)
        //     break
        //   case 3:
        //     this.dataSource = this.examList.slice(this.examList.length - 5)
        //     break
        //   default:
        //     this.dataSource = this.examList
        // }
      }
    },
  },
  computed: {
    ...mapGetters({
      isStoreExamEmpty: 'isEmpty',
      queryAllExams: 'queryAll',
    }),
    examList: function () {
      return this.queryAllExams
    },
    dataSource: function () {
      // 骗人的条件筛选
      switch (this.currentMenuIndex) {
        case 0:
          return this.examList
        case 1:
          return this.examList.slice(this.examList.length - 10, this.examList.length - 5)
        case 2:
          return this.examList.slice(0, this.examList.length - 10)
        case 3:
          return this.examList.slice(this.examList.length - 5)
        default:
          return this.examList
      }
    },
    labelCol: function () {
      return {
        xs: { span: 7 },
        sm: { span: 7 },
      }
    },
    wrapperCol: function () {
      return {
        xs: { span: 14 },
        sm: { span: 14 },
      }
    },
  },
  mounted() {
    if (this.isStoreExamEmpty) {
      // 从后端数据获取考试列表，适配前端卡片
      getExamCardList()
        .then((res) => {
          console.log(res)
          if (res.code === 0) {
            // this.examList = res.data
            // this.dataSource = res.data
            this.currentMenuIndex = 0
            // 为了store中的假数据初始化
            this.$store.commit(EXAM_MUTATION.INITIAL, { initialExamArr: res.data })
          } else {
            this.$notification.error({
              message: '获取考试列表失败',
              description: res.msg,
            })
          }
        })
        .catch((err) => {
          // 失败就弹出警告消息
          this.$notification.error({
            message: '获取考试列表失败',
            description: err.message,
          })
        })
    }
    // const storeExamData = this.queryAllExams
    // this.examList = storeExamData
    // this.dataSource = storeExamData
    // this.currentMenuIndex = 0
    this.queryAllExamPapers()
  },
}
</script>

<style lang="less" scoped>
.card-avatar {
  width: 48px;
  height: 48px;
  border-radius: 48px;
}

.ant-card-actions {
  background: #f7f9fa;

  li {
    float: left;
    text-align: center;
    margin: 12px 0;
    color: rgba(0, 0, 0, 0.45);
    width: 50%;

    &:not(:last-child) {
      border-right: 1px solid #e8e8e8;
    }

    a {
      color: rgba(0, 0, 0, 0.45);
      line-height: 22px;
      display: inline-block;
      width: 100%;

      &:hover {
        color: #1890ff;
      }
    }
  }
}

.new-btn {
  background-color: #fff;
  border-radius: 2px;
  width: 100%;
  height: 188px;
}

.meta-content {
  position: relative;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  height: 64px;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.operate-panel {
  height: 5rem;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
  border: 1px solid #e8e8e8;

  & > :first-child {
    margin-left: 1rem;
  }

  & > :last-child {
    margin-right: 1rem;
  }

  .tabs-menu {
    .tabs-item {
      font-size: 1rem;
      margin-right: 1rem;
      cursor: pointer;
    }

    .tabs-item.tabs-active {
      font-weight: 700;
      color: #1890ff;
      text-shadow: 0 0 2px rgba(26, 144, 255, 0.78);
    }
  }
}
</style>
